<?php
/**
 * User:chendenan
 * Created On 2022/3/13 0013 21:11
 */
namespace app\common\business;
use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;

class User {
    public $userObj = null ;
    public function __construct(){
        $this->userObj = new UserModel();
    }
    public function login($data){
        $redisCode = cache(config("redis.code_pre").$data['name']);
        if(empty($redisCode)  || $redisCode != $data['code'] ){
            throw new \think\Exception('不存在该验证码',config("status.not_code"));
        }
        //判断用户表是否存在
        //$user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        $user = $this->userObj->getUser($data['name']);
        if(!$user){
            $username = date("YmdHis").rand(10000000,99999999).'-'.$data['name'];
            $userData = [
                'username' => $username,
                //'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status'=> config("status.mysql.table_normal"),
            ];
            if(filter_var($data['name'], FILTER_VALIDATE_EMAIL)!=false){
                $userData['email'] = $data['name'];
            }else{
                $userData['phone_number'] = $data['name'];
            }
            try {
                $this->userObj->save($userData);
                $userId = $this->userObj->id;
            }catch (\Exception $e){
                throw new \think\Exception("数据库内部异常");
            }
        }else{
            $userId = $user->id;
            $username = $user->username;
            //更新数据表信息
            $user->type = $data['type'];
            $user->update_time = time();
            try {
                $user->save();
            }catch (\Exception $e){
                trace("User 数据库内部异常，登录失败","error");
                throw new \think\Exception("数据库内部异常，登录失败");
            }
        }
        //生成token
        $token = Str::getLoginToken($data['name']);
        $redisData = [
            'id' => $userId,
            'username' => $username,
        ];
        $res = cache(config("redis.token_pre").$token,$redisData,Time::userLoginExpiresTime($data['type']));
        return $res ? ["token"=>$token,"username"=>$username] : false ;
    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id){
        $user = $this->userObj->getUserById($id);
        if(!$user || $user->status != config("status.mysql.table_normal")){
            return [];
        }
        return $user->toArray();
    }
    /**
     * 返回正常用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserByUsername($username){
        $user = $this->userObj->getUserByUsername($username);
        if(!$user || $user->status != config("status.mysql.table_normal")){
            return [];
        }
        return $user->toArray();
    }
    public function update($id,$data){
        $user = $this->userObj->getUserById($id);
        if(!$user){
            throw new \think\Exception("不存在该用户");
        }
        if($user['user_count']==1){
            throw new \think\Exception("用户名超出最大修改次数");
        }
        //检查用户名是否存在
        $userResult = $this->getNormalUserByUsername($data['username']);
        if($userResult && $userResult['id'] != $id){
            throw new \think\Exception("该用户已经存在，请重新设置");
        }
        return $this->userObj->updateById($id,$data);
    }
}